package com.yequan.hbb.utils;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.v4.util.Pools;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;


import java.util.ArrayList;
import java.util.List;

public class ShufflingAdapter<T extends ShuffingBean> extends PagerAdapter {
    private Context context;
    private List<T> entries;
    private Pools.Pool<ImageView> pool = new Pools.SimplePool<>(4);

    @IdRes
    private int placeHolderImage;

    public ShufflingAdapter(Context context, List<T> entries, int placeHolderImage) {
        this.context = context;
        this.entries = new ArrayList<>(entries);
        T first = this.entries.get(0);
        T last = this.entries.get(entries.size() - 1);
        this.entries.add(0, last);
        this.entries.add(first);
        this.placeHolderImage = placeHolderImage;
    }

    @Override
    public int getCount() {
        return entries.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = pool.acquire();
        if (imageView == null) {
            imageView = new ImageView(context);
        }
        ImageUtils.loadImage(imageView, entries.get(position).getImageUrl(), placeHolderImage);
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
        pool.release((ImageView) object);
    }
}
